<?php

namespace app\api\logic;
use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
class Vip1688Logic extends BasicLogic
{

    /**
     * @desc   跨境场景下将商品加入铺货列表
     * @author luckyXiong
     * @date   2025-02-06
     */
    public function publish_product($params=[]){
        $product_id   = $params['product_id']??'';
        $base_url     = Config('Logisticskey.1688_info.base_url');
        $AppKey       = Config('Logisticskey.1688_info.VIP_AppKey');
        $access_token = Config('Logisticskey.1688_info.VIP_access_token');
        $url          = $base_url.Config('Logisticskey.1688_info.push_product').$AppKey;
        $offerIds     = [];
        $offerIds[]   = intval($product_id);
        $data = [
            'productIdList' =>json_encode($offerIds, JSON_UNESCAPED_UNICODE),
            'access_token'  =>$access_token,
        ];

        foreach ($data as $key => $value) {
            $data[$key] = urlencode($value);
        }
        $signature_url   = urladdparam($url,$data);
        $signature       = self::get_1688_signature(['url'=>$signature_url]);
        $data['_aop_signature']  =  $signature;
        $list   = HttpUtil::doGets($url,$data);
        return $list;
    }


    /**
     * @desc   获取1688商品的产品信息
     * @author luckyXiong
     * @date   2025-02-26
     */
    public function get_product_info($params=[]){
        $product_id   = $params['product_id']??'';
        $base_url     = Config('Logisticskey.1688_info.base_url');
        $AppKey       = Config('Logisticskey.1688_info.VIP_AppKey');
        $access_token = Config('Logisticskey.1688_info.VIP_access_token');
        $url          = $base_url.Config('Logisticskey.1688_info.get_product').$AppKey;
        //先去刊登;
        self::publish_product(['product_id'=>$product_id]);
        //然后获取sku信息
        $data         = [
            'productId'     =>$product_id,
            'access_token'  =>$access_token,
        ];
        $signature_url           = urladdparam($url,$data);
        $signature               = self::get_1688_signature(['url'=>$signature_url]);
        $data['_aop_signature']  = $signature;
        $list                    = HttpUtil::doGets($url,$data);
        $sku_list                = $list['productInfo']['skuInfos']??[];
        $product_name            = $list['productInfo']['subject']??'';
        $supplierLoginId         = $list['productInfo']['supplierLoginId']??'';
        $user_id                 = $list['productInfo']['supplierUserId']??'';
        //数据入库;
        return  [
            'sku_list'        =>$sku_list,
            'product_name'    =>$product_name,
            'supply_name'     =>$supplierLoginId,
            '1688_product_id' =>$product_id,
            'user_id'         =>$user_id,
        ];
    }


    /**
     * @desc   存储sku商品信息
     * @author luckyXiong
     * @date   2025-02-26
     */
    public function insert_skus($params=[]){
        $sku_list     = $params['sku_list']??'';
        $product_id   = $params['1688_product_id']??'';
        $supply_name  = $params['supply_name']??'';
        $product_name = $params['product_name']??'';
        $user_id      = $params['user_id']??'';
        $insert_arr   = [];
        //查看当前厂家是否存在;
        if($supply_name){
            $exist_supply = Db::name('supply')->where(['supply_name'=>$supply_name])->find();
        }
        if(!$exist_supply){
            $supply_id = Db::name('supply')->insertGetId(
                [
                    'supply_name' =>$supply_name,
                    'user_id'     =>$user_id,
                    'created_time'=>date("Y-m-d H:i:s", time())
                ]);
        }else{
            $supply_id = $exist_supply['id'];
            Db::name('supply')->where(['supply_id'=>$supply_id])->update(
                [
                    'user_id'     =>$user_id,
                ]);
        }


        //获取表中是否存在数据;
        $exist_info = Db::name('product_1688')->where(['1688_product_id'=>$product_id])->column('skuId');
        if($exist_info){
            foreach($sku_list  as $v){

                if(in_array($v['skuId'],$exist_info)){
                    continue;
                }
                $product_image              = $v['attributes'][0]['skuImageUrl']??'';
                $temp['1688_product_id']    = $product_id;
                $temp['1688_product_image'] = $product_image ? Config('Logisticskey.1688_info.image_url').$product_image:'';
                $temp['1688_product_url']   = Config('Logisticskey.1688_info.1688_url').$product_id.'.html';
                $temp['skuId']              = $v['skuId'];
                $temp['specId']             = $v['specId'];
                $temp['1688_product_name']  = $product_name;
                $temp['varient_colour']     = $v['attributes'][0]['attributeValue']??'';
                $temp['varient_size']       = $v['attributes'][1]['attributeValue']??'';
                $temp['supply_id']          = $supply_id;
                $temp['create_time']        = date("Y-m-d H:i:s", time());
                $insert_arr[]               = $temp;
            }
        }else{
            foreach($sku_list  as $v){
                $product_image              = $v['attributes'][0]['skuImageUrl']??'';
                $temp['1688_product_id']    = $product_id;
                $temp['1688_product_image'] = $product_image ? Config('Logisticskey.1688_info.image_url').$product_image:'';
                $temp['1688_product_url']   = Config('Logisticskey.1688_info.1688_url').$product_id.'.html';
                $temp['skuId']              = $v['skuId'];
                $temp['specId']             = $v['specId'];
                $temp['1688_product_name']  = $product_name;
                $temp['varient_colour']     = $v['attributes'][0]['attributeValue']??'';
                $temp['varient_size']       = $v['attributes'][1]['attributeValue']??'';
                $temp['supply_id']          = $supply_id;
                $temp['create_time']        = date("Y-m-d H:i:s", time());
                $insert_arr[]               = $temp;
            }
        }

        if($insert_arr){
            Db::name('product_1688')->insertAll($insert_arr);
        }
        return  true;
    }


    /**
     * @desc   获取仓库产品信息接口
     * @author luckyXiong
     * @date   2025-02-06
     */
    public function get_skus_info($params=[]){
        $seller_sku = $params['seller_sku']??'';
        $limit      = getIsset($params,'limit',10);
        $where      = [];
        if($seller_sku){
            $where[] = ['seller_sku', 'like', '%' . $seller_sku . '%'];
        }

        $res   = Db::name('product_seller_sku')
            ->field('id,seller_sku,image_info')
            ->where($where)
            ->order('created_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];
        foreach($list as $k=>$v){
            $list[$k]['image_info'] = $v['image_info'] ?  : Config('Logisticskey.product_image_default');
        }
        return [
            'list'   => $list,
            'total'  => $res->total(),
        ];
    }


    /**
     * @desc   手动指定绑定关系
     * @author luckyXiong
     * @date   2025-02-28
     */
    public function bind_sku_1688($params=[]){
           $seller_sku  = $params['seller_sku']??'';


    }



    /**
     * @desc   1688创建采购单接口
     * @author luckyXiong
     * @date   2025-02-28
     */
    public function createOrder($params = []){
        //获取当前的创建账户;
        $account_1688 = $params['account_1688']??'';
        $sku_list     = $params['sku_list']??'';
        $message      = $params['message']??'';
        $info         = Db::name('1688_token')->where(['account_1688'=>$account_1688])->find();
        $base_url     = Config('Logisticskey.1688_info.base_url');
        $AppKey       = Config('Logisticskey.1688_info.VIP_AppKey');
        $url          = $base_url.Config('Logisticskey.1688_info.cross_order').$AppKey;
        //测试数据 02-10
        $addressParam = [
            "fullName"    => "帆洲科技",
            "mobile"      => $info['phone'],
            "postCode"    => "430000",
            "provinceText"=> "湖北省",
            "areaText"    => $info['area_text'],
            "cityText"    => "武汉市",
            "address"     => $info['address'],
        ];

        $data         = [
            'flow'          =>'general',
            'message'       =>$message,
            'addressParam'  =>json_encode($addressParam, JSON_UNESCAPED_UNICODE),
            'cargoParamList'=>json_encode($sku_list, JSON_UNESCAPED_UNICODE),
            'access_token'  =>$info['access_token'],
        ];
        foreach ($data as $key => $value) {
            $data[$key] = urlencode($value);
        }
        $signature_url           = urladdparam($url,$data);
        $signature               = self::get_1688_signature(['url'=>$signature_url]);
        $data['_aop_signature']  = $signature;
        $response                = HttpUtil::doGets($url,$data);
        if (isset($response['success']) && $response['success']) {
            $res_info = $response['result']['orderId']??'';
        } else {
            $res_info = $response['Responses']??'';
        }
        return $res_info;
    }



    /**
     * @desc   1688订单取消接口
     * @author luckyXiong
     * @date   2025-02-27
     */
    public function cancelOrder($params = []){
        //1688订单号
        $order_number = $params['1688_order_number']??'';
        $access_token = Config('Logisticskey.1688_info.VIP_access_token');
        $base_url     = Config('Logisticskey.1688_info.base_url');
        $AppKey       = Config('Logisticskey.1688_info.VIP_AppKey');
        $url          = $base_url.Config('Logisticskey.1688_info.cancel_order').$AppKey;
        $data         = [
            'tradeID'       =>$order_number,
            'webSite'       =>'1688',
            'cancelReason'  =>'buyerCancel',
            'access_token'  =>$access_token,
        ];
        $signature_url   = urladdparam($url,$data);
        $signature       = self::get_1688_signature(['url'=>$signature_url]);
        $data['_aop_signature']  =  $signature;
        $res       = HttpUtil::doGets($url,$data);
        return $res;
    }

    /**
     * @desc   获取旺旺聊天url
     * @author luckyXiong
     * @date   2025-02-28
     */
    public function get_wangwang_url($params=[]){
        $user_id      = $params['user_id']??'';
        $access_token = Config('Logisticskey.1688_info.VIP_access_token');
        $base_url     = Config('Logisticskey.1688_info.base_url');
        $AppKey       = Config('Logisticskey.1688_info.VIP_AppKey');
        $url          = $base_url.Config('Logisticskey.1688_info.wangwang_url').$AppKey;
        $data         = [
            'toOpenUid'     =>$user_id,
            'access_token'  =>$access_token,
        ];
        $signature_url   = urladdparam($url,$data);
        $signature       = self::get_1688_signature(['url'=>$signature_url]);
        $data['_aop_signature'] = $signature;
        $res       = HttpUtil::doGets($url,$data);
        $url       =  $res['result']['result']??'';
        return  ['url'=>$url];
    }


    /**
     * @desc   获取旺旺聊天url
     * @author luckyXiong
     * @date   2025-02-28
     */
    public function get_logistics($params=[]){
        $order_number = $params['1688_order_number']??'';
        $access_token = Config('Logisticskey.1688_info.VIP_access_token');
        $base_url     = Config('Logisticskey.1688_info.base_url');
        $AppKey       = Config('Logisticskey.1688_info.VIP_AppKey');
        $url          = $base_url.Config('Logisticskey.1688_info.order_logistics').$AppKey;
        $companys     = Config('Logisticskey.track_list');
        $data         = [
            'orderId'       =>$order_number,
            'webSite'       =>'1688',
            'access_token'  =>$access_token,
        ];
        $signature_url          = urladdparam($url,$data);
        $signature              = self::get_1688_signature(['url'=>$signature_url]);
        $data['_aop_signature'] = $signature;
        $res                    = HttpUtil::doGets($url,$data);
        $track_number           = $res['result'][0]['logisticsBillNo']??'';
        $track_id               = $res['result'][0]['logisticsCompanyId']??'';
        $track_name             = $res['result'][0]['logisticsCompanyName']??'';
        foreach ($companys as $key => $company) {
            if (strpos($track_name, $company) !== false) {
                $matchedKey = $key;
                break;
            }
        }
        if ($matchedKey !== false) {
            $data = [
                'track_number'=>$track_number,
                'track_id'    =>$matchedKey,
                'track_name'  =>$companys[$matchedKey],
            ];
        }else{
            $data = [
                'track_number'=>$track_number,
                'track_id'    =>$track_id,
                'track_name'  =>$track_name,
            ];
        }
        return $data;
    }

    /**
     * @desc   获取订单物流轨迹
     * @author luckyXiong
     * @date   2025-02-28
     */
    public function get_logistics_list($params=[]){
        $order_number = $params['1688_order_number']??'';
        $access_token = Config('Logisticskey.1688_info.VIP_access_token');
        $base_url     = Config('Logisticskey.1688_info.base_url');
        $AppKey       = Config('Logisticskey.1688_info.VIP_AppKey');
        $url          = $base_url.Config('Logisticskey.1688_info.logistics_list').$AppKey;
        $data         = [
            'orderId'       =>$order_number,
            'webSite'       =>'1688',
            'access_token'  =>$access_token,
        ];
        $signature_url          = urladdparam($url,$data);
        $signature              = self::get_1688_signature(['url'=>$signature_url]);
        $data['_aop_signature'] = $signature;
        $res                    = HttpUtil::doGets($url,$data);
        $track_number           = '';
        $track_list             = '';
        if(isset($res['success']) && $res['success']){
              $track_number = $res['logisticsTrace'][0]['logisticsBillNo']??'';
              $track_list   = $res['logisticsTrace'][0]['logisticsSteps']??'';
              usort($track_list, function ($a, $b) {
                return strtotime($b['acceptTime']) - strtotime($a['acceptTime']);
              });
        }
        return  [
            'track_number'=>$track_number,
            'track_list'  =>$track_list
        ];
    }


    /**
     * @desc   指定配对关系
     * @author luckyXiong
     * @date   2025-03-03
     */
    public function change_pair($params=[]){
       $seller_sku       = $params['seller_sku']??'';
       $product_1688_id  = $params['1688_product_id']??'';
       $product_1688_url = $params['1688_product_url']??'';
       $id               = $params['id']??'';
       $specId           = $params['specId']??'';

       if(!$seller_sku){
           return  $this->jsonMessage(201,false,'seller_sku不能为空!',null);
       }

       if(!$product_1688_id){
           return  $this->jsonMessage(201,false,'1688产品ID不能为空!',null);
       }

        if(!$product_1688_url){
            return  $this->jsonMessage(201,false,'1688url不能为空!',null);
        }

        if(!$specId){
            return  $this->jsonMessage(201,false,'specId不能为空!',null);
        }

       try{
            Db::startTrans();
            //同步更新产品的sku信息表和1688产品信息表
            Db::name('product_1688')->where(['id'=>$id])->update(
                [
                    'seller_sku' => $seller_sku,
                    'is_pair'    => 1,
                    'update_time'=> date("Y-m-d H:i:s", time()),
                ]
            );

            Db::name('product_seller_sku')->where(['seller_sku'=>$seller_sku])->update(
               [
                   '1688_product_url' => $product_1688_url,
                   '1688_product_id'  => $product_1688_id,
                   'specId'           => $specId,
                   'is_pair'          => 1,
                   'update_time'      => date("Y-m-d H:i:s", time()),
               ]
            );
            Db::commit(); // 提交事务
            $this->jsonMessage(200, true,'操作成功',null);
        }catch (Exception $e){
            Db::rollback(); // 回滚事务
            $this->jsonMessage(201,false,$e->getMessage(),null);
        }

    }


    /**
     * @desc   删除产品接口
     * @author luckyXiong
     * @date   2025-03-03
     */
    public function delete_1688($params=[]){
        $id    = $params['id']??'';
        //获取当前1688产品是否绑定sku
        $exist_seller_sku = Db::name('product_1688')->where(['id'=>$id])->value('seller_sku');
        if($exist_seller_sku){
            Db::name('product_seller_sku')->where(['seller_sku'=>$exist_seller_sku])->update(
                [
                    '1688_product_url' => '',
                    '1688_product_id'  => '',
                    'specId'           => '',
                    'is_pair'          => 0,
                    'update_time'      => date("Y-m-d H:i:s", time()),
                ]
            );
        }
        Db::name('product_1688')->where(['id'=>$id])->delete();
    }


    /**
     * @desc   更换配对关系
     * @author luckyXiong
     * @date   2025-03-03
     */
    public function update_1688($params=[]){
        $seller_sku       = $params['seller_sku']??'';
        $old_seller_sku   = $params['old_seller_sku']??'';
        $product_1688_id  = $params['1688_product_id']??'';
        $product_1688_url = $params['1688_product_url']??'';
        $id               = $params['id']??'';
        $specId           = $params['specId']??'';


        try{
            Db::startTrans();
            //同步更新产品的sku信息表和1688产品信息表
            Db::name('product_1688')->where(['id'=>$id])->update(
                [
                    'seller_sku' => $seller_sku,
                    'update_time'=> date("Y-m-d H:i:s", time()),
                ]
            );

            //旧的配对关系取消
            Db::name('product_seller_sku')->where(['seller_sku'=>$old_seller_sku])->update(
                [
                    '1688_product_url' => '',
                    '1688_product_id'  => '',
                    'specId'           => '',
                    'is_pair'          => 0,
                    'update_time'      => date("Y-m-d H:i:s", time()),
                ]
            );

            //绑定新的配对关系
            Db::name('product_seller_sku')->where(['seller_sku'=>$seller_sku])->update(
                [
                    '1688_product_url' => $product_1688_url,
                    '1688_product_id'  => $product_1688_id,
                    'specId'           => $specId,
                    'is_pair'          => 1,
                    'update_time'      => date("Y-m-d H:i:s", time()),
                ]
            );
            Db::commit(); // 提交事务
            $this->jsonMessage(200, true,'操作成功',null);
        }catch (Exception $e){
            Db::rollback(); // 回滚事务
            $this->jsonMessage(201,false,$e->getMessage(),null);
        }

    }


    /**
     * @desc   解除配对关系
     * @author luckyXiong
     * @date   2025-03-03
     */
    public function release_1688($params=[]){
        $old_seller_sku   = $params['old_seller_sku']??'';
        $id               = $params['id']??'';
        try{
            Db::startTrans();
            //同步更新产品的sku信息表和1688产品信息表
            Db::name('product_1688')->where(['id'=>$id])->update(
                [
                    'seller_sku' => '',
                    'is_pair'    => 0,
                    'update_time'=> date("Y-m-d H:i:s", time()),
                ]
            );

            //旧的配对关系取消
            Db::name('product_seller_sku')->where(['seller_sku'=>$old_seller_sku])->update(
                [
                    '1688_product_url' => '',
                    '1688_product_id'  => '',
                    'specId'           => '',
                    'is_pair'          => 0,
                    'update_time'      => date("Y-m-d H:i:s", time()),
                ]
            );

            Db::commit(); // 提交事务
            $this->jsonMessage(200, true,'操作成功',null);
        }catch (Exception $e){
            Db::rollback(); // 回滚事务
            $this->jsonMessage(201,false,$e->getMessage(),null);
        }
    }


    /**
     * @desc   1688采购列表下单接口
     * @author luckyXiong
     * @date   2025-03-27
     */
    public function submit_1688_order($params){
           $purchase_numbers = $params['purchase_numbers']??[];
           foreach($purchase_numbers as $v){
               // 队列处理
               MqTaskPushLogic::mq_task_push(
                   '',
                   MqQueueName::QUEUE_ORDER_ALI_QUEUE,
                   ['purchase_number'=>$v],
                   false
               );
           }
           //批量更新订单的下单状态;
           Db::name('purchase_manual')->whereIn('purchase_number',$purchase_numbers)->update(
               [
                   '1688_submit_status'=>2,
                   'update_time'       =>date("Y-m-d H:i:s", time()),
               ]
           );
           return  $this->jsonMessage(200, true,'操作成功',null);
    }


    /**
     * @desc   1688采购列表下单接口
     * @author luckyXiong
     * @date   2025-03-27
     */
    public function do_submit_1688($message){
           $purchase_number = $message['purchase_number']??'';
           //组装请求数据;
           $field = 'p.purchase_number,p.1688_account,p.1688_remark,p.remark,
                     d.1688_product_id,d.specId,d.purchase_quantity';
           $info  = Db::name('purchase_manual')->alias('p')
                      ->field($field)
                      ->leftJoin('purchase_manual_detail d', 'p.purchase_number = d.purchase_number')
                      ->where(['p.purchase_number'=>$purchase_number])
                      ->select()
                      ->toArray();
           $current_info = current($info);
           $sku_list     = [];
           foreach($info as $v){
                 if($v['specId']){
                     $temp['offerId']  = $v['1688_product_id'];
                     $temp['specId']   = $v['specId'];
                     $temp['quantity'] = $v['purchase_quantity'];
                     $sku_list[]       = $temp;
                   }
           }
           $data = [
                   'account_1688'=>$current_info['1688_account']??'',
                   '1688_remark' =>$current_info['message']??'',
                   'sku_list'    =>$sku_list,
           ];
           if($sku_list){
               $order_1688_id = self::createOrder($data);
           }

           if($order_1688_id){
               Db::name('purchase_manual')->where(['purchase_number'=>$purchase_number])->update(
                   [
                       '1688_order_number'=>$current_info['1688_account'].'-'.$order_1688_id,
                       'update_time'      =>date("Y-m-d H:i:s", time()),
                   ]
                );
              }
          return  true;
    }















    /**
     * @desc    发起授权请求签名串组装
     * @date    2025-02-07
     * @author  zhangheng
     */
    public function get_1688_signature($params = [])
    {
        $appSecret = Config('Logisticskey.1688_info.VIP_AppSecret');
        $url       = $params['url']??'';
        // 使用 parse_url() 函数解析 URL
        $parsedUrl   = parse_url($url);
        $path        = str_replace('/openapi/', '', $parsedUrl['path']);
        $queryString = $parsedUrl['query']??'';
        $aliParams   = [];
        parse_str($queryString, $queryParams);
        foreach ($queryParams as $key => $val) {
            $aliParams[] = $key . $val;
        }
        sort($aliParams);
        $sign_str = $path.join('', $aliParams);
        return strtoupper(bin2hex(hash_hmac("sha1", $sign_str, $appSecret, true)));
    }
}